import { ETTask } from "../../../Support/Share/Lib/Async/ETTask";
import { Dictionary } from "../../../Support/Share/Lib/Dictionary";
import { CoroutineLock } from "./CoroutineLock";
import { CoroutineLockQueue } from "./CoroutineLockQueue";

export class CoroutineLockQueueType {

    private readonly type: number;
    private readonly coroutineLockQueues: Dictionary<number, CoroutineLockQueue> = new Dictionary<number, CoroutineLockQueue>();

    constructor(type: number) {
        this.type = type;
    }

    private Get(key: number): CoroutineLockQueue {
        let queue = this.coroutineLockQueues.TryGetValue(key);
        return queue;
    }

    private New(key: number): CoroutineLockQueue {
        let queue = CoroutineLockQueue.Create(this.type, key);
        this.coroutineLockQueues.Add(key, queue);
        return queue;
    }

    private Remove(key: number): void {
        let queue = this.coroutineLockQueues.Remove(key);
        if (queue) {
            queue.Recycle();
        }
    }

    public async Wait(key: number, time: number): Promise<CoroutineLock> {
        let queue = this.Get(key) ?? this.New(key);
        return await queue.Wait(time);
    }

    public Notify(key: number, level: number): void {
        let queue = this.Get(key);
        if (queue == null) {
            return;
        }

        if (queue.Count == 0) {
            this.Remove(key);
        }

        queue.Notify(level);
    }

}